<template>
  <div id="box">
    <Button @click="change" class="fileBtnHoverBlue">显示路网</Button>
    <div id="map" />
  </div>
</template>
<script>

import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { Map, View } from "ol";
import { fromLonLat } from "ol/proj";

export default {
  data() {
    return {
      map: null,
      mapView: {
        center: fromLonLat([120, 25]), // 地图中心点
        zoom: 7, // 初始缩放级别
        minZoom: 1, // 最小缩放级别
        maxZoom: 22, // 最大缩放级别
      },
      // 瓦片引入地址 nginx
      // mapUrl: `http://127.0.0.1:9098/tiles/{z}/{x}/{y}.png`
      // 瓦片本地引入 瓦片等级越高加载编译越慢
      // 在 public 下新建 tiles 文件夹，将下好的瓦片放进去
      mapUrl: `https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s,m&gl=CN&x={x}&y={y}&z={z}`,
      mapUrl2: `http://gac-geo.googlecnapps.cn/maps/vt?lyrs=s&x={x}&y={y}&z={z}`,
      mapType: 1,
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    // 初始化地图
    initMap() {
      let tileLayer = new TileLayer({
        source: new XYZ({
          url: this.mapUrl,
        }),
      });
      let tileLayer2 = new TileLayer({
        source: new XYZ({
          url: this.mapUrl2,
        }),
        visible: false,
      });
      this.map = null;
      this.map = new Map({
        layers: [tileLayer, tileLayer2],
        view: new View(this.mapView),
        target: "map", // 将地图注入到 dom 元素中，此处写 dom id
      });
    },
    change() {
      if (this.mapType == 1) {
        this.mapType = 2;
        this.map.getLayers().item(0).setVisible(false);
        this.map.getLayers().item(1).setVisible(true);
      } else {
        this.mapType = 1;
        this.map.getLayers().item(0).setVisible(true);
        this.map.getLayers().item(1).setVisible(false);
      }
    },
  },
};
</script>

<style scoped>

#map {
  width: 100%;
  height: 100%;
  position: absolute;
}
.fileBtnHoverBlue {
  position: absolute;
  z-index: 10;
  right: 10px;
  top: 10px;
}
.fileBtnHoverBlue:hover {
  background-color: #2db7f5;
  color: white;
}
</style>


